﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using System.IO;
using System.Xml;

namespace VirtualBook
{
    public class PageLoader
    {
        public static List<PageSet> GetPages()
        {
            List<PageSet> pages = new List<PageSet>();

            List<string> files = GetFileNamesFromXML();

            if (files.Count == 0)
            {
                return pages;
            }

            for (int i = 1; i < files.Count; i+=2)
            {
                Uri u1 = new Uri(files[i - 1], UriKind.RelativeOrAbsolute);
                Uri u2 = new Uri(files[i], UriKind.RelativeOrAbsolute);

                BitmapImage b1 = new BitmapImage(u1);
                BitmapImage b2 = new BitmapImage(u2);

                pages.Add(new PageSet(b1, b2));
            }

            if (files.Count % 2 != 0)
            {
                Uri u3 = new Uri(files[files.Count - 1], UriKind.RelativeOrAbsolute);
                BitmapImage b3 = new BitmapImage(u3);

                pages.Add(new PageSet(b3));
            }

            return pages;
        }

        private static List<string> GetFileNamesFromXML()
        {
            List<string> filenames = new List<string>();

            XmlReader reader = XmlReader.Create("ImagePaths.xml");

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "ImageFilePath")
                    {
                        filenames.Add(reader.ReadElementContentAsString());
                    }
                }
            }

            reader.Close();

            return filenames;
        }
    }
}
